Page({
  data: {
    info: { images: [] },
    images: [], // 图片列表
    maxImages: 9,// 最大图片数
    content: ''
  },
  delIt(e) {
    wx.showModal({
      title: '提示',
      content: '是否删除当前图片?',

    }).then(r => {
      if (r.confirm) {
        const index = e.currentTarget.dataset.index
        this.data.info.images.splice(index, 1)
        this.setData({
          info: this.data.info
        })
      }
    })

  },
  onLoad(e) {
    if (e.nid) {
      this.data.info.id = e.nid
      this.getInfo()
    }
  },

  async getInfo() {
    const res = await getApp().$request('/api/getNoticeById', 'POST', { nid: this.data.info.id })
    if (!res.data.images) {
      res.data.images = []
    }
    this.setData({
      info: res.data
    })
  },
  inputTitle(e) {
    this.data.info.title = e.detail.value
  },
  inputContent(e) {
    this.data.info.content = e.detail.value
  },
  // 添加图片
  async addImage() {
    const res = await getApp().$upload('notice')
    this.data.info.images.push(res.data)
    this.setData({
      'info.images': this.data.info.images
    })
  },

  // 发布动态
  async publishPost() {
    if (!this.data.info.title) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      })
      return
    }

    if (!this.data.info.content) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }

    const datas = {
      title: this.data.info.title,
      content: this.data.info.content.replace(/\n/g, '<br/>'),
      image_url: this.data.info.images.join(','),
      createdAt: getApp().getNowTime()
    }

    console.log(datas.content);

    let res = null
    if (!this.data.info.id) {
      res = await getApp().$request('/api/addNotice', 'POST', datas)
    } else {
      datas.id = this.data.info.id
      res = await getApp().$request('/api/updateNotice', 'POST', datas)
    }


    // 此处添加表单验证和上传逻辑
    wx.showToast({
      title: '发布成功！',
      icon: 'success'
    });
    this.setData({
      title: '',
      content: '',
      images: []
    })
    wx.navigateTo({
      url: '/pages/noticeDetail/noticeDetail?nid=' + res.data,
    })
  }
});
